import { createRouter, createWebHashHistory } from "vue-router";

import { localCache } from "@/utils/cache";
import { LOGIN_TOKEN } from "@/global/constants";
import { firstMenu } from "@/utils/map-menu";

const router = createRouter({
  history: createWebHashHistory(),
  // 映射关系: path => component
  routes: [
    {
      path: "/",
      redirect: "/main"
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../views/login/login.vue")
    },
    {
      path: "/main",
      name: "main",
      component: () => import("../views/home/home.vue"),
      children: []
    },
    {
      path: "/:pathMatch(.*)",
      component: () => import("../views/not-found/NotFound.vue")
    }
  ]
});

// // 1.获取所有的路由
// const localRoutes = [
//   {
//     path: "/main/analysis/overview",
//     component: () => import("../views/analysis/overview/overview.vue")
//   },
//   {
//     path: "/main/analysis/dashboard",
//     component: () => import("../views/analysis/dashboard/dashboard.vue")
//   },
//   {
//     path: "/main/system/user",
//     component: () => import("../views/system/user/user.vue")
//   },
//   {
//     path: "/main/system/role",
//     component: () => import("../views/system/role/role.vue")
//   }
// ];

// // // 2.动态的添加路由
// router.addRoute("main", localRoutes[0]);
// router.addRoute("main", localRoutes[1]);

// 前置守卫
// 参数: to(跳转到的位置)/from(从哪里跳转过来)
// 返回值: 返回值决定导航的路径(不返回或者返回undefined, 默认跳转)
// 举个栗子: / => /main
// to: /main from: / 返回值: /abc
router.beforeEach((to) => {
  // 只有登陆成功有token后，方可真正进入到home页
  const token = localCache.getCache(LOGIN_TOKEN);

  if (to.path.startsWith("/main") && !token) {
    return "/login";
  }

  // 如果是进入到main里
  if (to.path === "/main" && token) {
    return firstMenu?.url;
  }
});

export default router;
